package com.ypf.controller;

import com.google.code.kaptcha.Producer;
import com.ypf.domain.ResponseResult;
import com.ypf.domain.vo.LoginVo;
import com.ypf.service.LoginService;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

@RestController
@CrossOrigin
public class LoginController {

    private final Producer producer;

    @Autowired
    private LoginService loginService;

    @Autowired
    public LoginController(Producer producer){
        this.producer = producer;
    }

    @GetMapping("/user/vc.jpg")
    public String getVerifyCode(HttpSession session) throws IOException {
        // 1 生成验证码
        String text = producer.createText();
        System.out.println(text);
        // 2 放入session 日后可以换成redis 实现
        session.setAttribute("captcha",text);
        // 3 生成图片
        BufferedImage bi = producer.createImage(text);
        FastByteArrayOutputStream fos = new FastByteArrayOutputStream();
        ImageIO.write(bi,"jpg",fos);
        // 4 返回base64
        return Base64.encodeBase64String(fos.toByteArray());
    }

    @PostMapping("/user/login")
    public ResponseResult login(@RequestBody LoginVo loginVo, HttpSession session){

        String captcha = (String) session.getAttribute("captcha");

        return  loginService.login(loginVo,captcha);
    }

}
